<template>
  <div>
    <input type="file" @change="handleFileUpload" />
    <canvas ref="canvas" :width="pageWidth" :height="pageHeight"></canvas>
  </div>
</template>

<script>
import JSZip from "jszip";

export default {
  data() {
    return {
      pageWidth: 794, // A4尺寸
      pageHeight: 1123,
    };
  },
  methods: {
    async handleFileUpload(e) {
      const file = e.target.files[0];
      const arrayBuffer = await file.arrayBuffer();
      const zip = new JSZip();
      const doc = await zip.loadAsync(arrayBuffer);
      const xml = await doc.file("word/document.xml").async("text");
      this.renderCanvas(xml);
    },
    renderCanvas(xml) {
      const ctx = this.$refs.canvas.getContext("2d");
      ctx.clearRect(0, 0, this.pageWidth, this.pageHeight);

      // 解析XML并绘制（示例：段落渲染）
      const parser = new DOMParser();
      const xmlDoc = parser.parseFromString(xml, "text/xml");
      const paragraphs = xmlDoc.getElementsByTagName("w:p");
      let y = 50;
      Array.from(paragraphs).forEach((p) => {
        const text = p.getElementsByTagName("w:t")[0]?.textContent || "";
        console.log("text---", text);
        // ctx.fillStyle = this.extractColor(p);
        // ctx.fillStyle = '#424242'
        ctx.fillStyle = 'red'
        ctx.font = "16px Arial";
        this.renderText(ctx, text, 50, y, 700); // 700为行宽限制
        y += 30; // 行间距
      });
    },
    renderText(ctx, text, x, y, maxWidth) {
      const words = text.split(" ");
      let line = "";
      words.forEach((word) => {
        const testLine = line + word + " ";
        const metrics = ctx.measureText(testLine);
        if (metrics.width > maxWidth) {
          ctx.fillText(line, x, y);
          line = word + " ";
          y += 20; // 行高
        } else {
          line = testLine;
        }
      });
      ctx.fillText(line, x, y); // 绘制最后一行
    },
  },
};
</script>